var express = require('express');
var router = express.Router();
var mysql = require('mysql');

var connection = mysql.createConnection({ host: '192.168.23.1', port: 3306, user: 'root', password: 'root', database: 'mydb' });
// 添加新闻
router.post('/addnews', function(req, res, next) {
        var title = req.body.newstitle;
        var content = req.body.newscontent;
        var img = req.body.newsimg;
        var url = req.body.newsurl;
        var data = req.body.newsdata;
        var style = req.body.newsstyle;
        // console.log(data);
        var mysqlNews = 'INSERT INTO `news`( `title`,`content`,`img`,`time`,`src`) VALUES (?,?,?,?,?)';
        var addNews = [title, content, img, data, style];
        // console.log(mysqlNews)
        connection.query(mysqlNews, addNews, function(err, rows, fd) {
            console.log(rows.insertId)
            var inserId = rows.insertId
            idNews(inserId)

        })

        function idNews(inserId) {
            connection.query('SELECT * FROM `news` WHERE id=?', inserId, function(err, rows, fd) {
                    if (err) {
                        console.log(err)

                    } else {
                        console.log(rows);
                        res.send(rows)
                    }
                })
                // })
        }
    })
    // 删除新闻
router.post('/deleteNews', function(req, res, next) {
    var myid = req.body.myid;
    console.log(myid);
    connection.query('DELETE FROM `news` WHERE id=?', myid, function(err, rows, fd) {
        if (err) {
            console.log(err);
        } else {
            res.send(rows)

        }
    })
});
// 修改新闻
router.post('/alternews', function(req, res, next) {
    var title = req.body.newstitle;
    var content = req.body.newscontent;
    var img = req.body.newsimg;
    var url = req.body.newsurl;
    var data = req.body.newsdata;
    var style = req.body.newsstyle;
    var id = req.body.alterid;
    var alternew = 'UPDATE `news` SET `title`=?,`time`=?,`content`=?,`src`=?,`img`=? WHERE id=' + id;
    var select = 'SELECT * FROM `news` WHERE id=?';
    // var mysqlNews = 'INSERT INTO `news`( `title`,`content`,`img`,`time`,`src`) VALUES (?,?,?,?,?)';
    var addNews = [title, content, img, data, style];
    connection.query(alternew, addNews, function(err, rows, fd) {
        if (err) {
            console.log(err);
            return
        }
        connection.query(select, id, function(err, row, fd) {
            if (err) {
                res.send(err);
            } else {
                res.send(row, 200)
            }
        })
    })
});

module.exports = router;